<script lang="ts" setup>
import api from '@/api/http.api'
import { onMounted, reactive, ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { use } from 'echarts';

onMounted(() => { getList() })

// 搜索
const searchKey = ref('')
const onSearch = () => {
  data.pageIndex = 1
  data.pageSize = 10
  getList()
}

// 列表
const data = reactive({
  list: [],
  loading: false,
  pageSize: 10,
  pageIndex: 1,
  total: 0
})
const getList = () => {
  const params = {
    pageIndex: data.pageIndex,
    pageSize: data.pageSize,
    searchKey: searchKey.value
  }
  data.loading = true
  api.getUserList(params).then(res => {
    const { total, list } = res.data
    data.list = list || []
    data.total = total
    data.loading = false
  }).catch(err => {
    data.loading = false;
    ElMessage({type: 'error', message: "服务器出错了，请联系大炮"})
  })
}
const onSizeChange = (value: number) => {
  data.pageSize = value
  getList()
}
const onCurrentChange = (value: number) => {
  data.pageIndex = value
  getList()
}

// 删除
const dialogVisible = ref(false)
const deleteUser = ref<any>(null)
const onDelete = (user: any) => {
  deleteUser.value = user
  dialogVisible.value = true
}
const onDeleteConfim = () => {
  api.deleteUser({id: deleteUser.value.id}).then(res => {
    if(res) {
      ElMessage({type: 'success', message: res.message})
      getList()
    }
  })
  dialogVisible.value = false;
}

// 新增、编辑
const drawerVisible = ref(false)
const drawerType = ref(1)               // 1=新增 2=编辑
const drawerUser = ref<any>(null)
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  id: '',
  name: '',
  username: '',
  userpwd: '',
  sex: '',
  age: ''
})
const rules = reactive<FormRules<typeof ruleForm>>({
  name: [{ required: true, message: '必填', trigger: 'blur' }],
  username: [{ required: true, message: '必填', trigger: 'blur' }],
  userpwd: [{ required: true, message: '必填', trigger: 'blur' }],
  sex: [{ required: true, message: '必选', trigger: 'blur' }],
  age: [{ required: true, message: '必填', trigger: 'blur' }],
})
const sexOptions = ref(['男', '女', '保密'])
// 打开drawer
const showDrawer = (type: number, user?: any) => {
  drawerType.value = type
  drawerUser.value = user
  drawerVisible.value = true
  if(user) {
    const { id, name, username, userpwd, sex, age } = user
    ruleForm.id = id
    ruleForm.name = name
    ruleForm.username = username
    ruleForm.userpwd = userpwd
    ruleForm.sex = sex
    ruleForm.age = age
  }
}
// drawer关闭回调
const closeDrawer = () => {
  resetForm(ruleFormRef.value)
  drawerUser.value = null
  ruleForm.id = ''
  ruleForm.name = ''
  ruleForm.username = ''
  ruleForm.userpwd = ''
  ruleForm.sex = ''
  ruleForm.age = ''
}
// 表单提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      const { id, name, username, userpwd, sex, age } = ruleForm
      const params = { id, name, username, userpwd, sex, age }

      // 新增
      if(drawerType.value === 1) {
        api.addUser(params).then(res => {
          if(res) {
            ElMessage({type: 'success', message: res.message})
            getList()
            drawerVisible.value = false
          }
        })
      }
      // 编辑
      if(drawerType.value === 2) {
        api.updateUser(params).then(res => {
          if(res) {
            ElMessage({type: 'success', message: res.message})
            getList()
            drawerVisible.value = false
          }
        })
      }
      
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<template>
  <div class="test">
    <div class="z-option" style="width: 820px;">
      <div class="option-left">
        <div class="option-item">
          <el-input v-model="searchKey" size="large" placeholder="请输入姓名关键字" :suffix-icon="Search" @change="onSearch" />
        </div>
        <div class="option-item">
          <el-button type="primary" size="large" @click="onSearch">搜索</el-button>
        </div>
      </div>
      <div class="option-right">
        <button class="btn" @click="showDrawer(1)">新增用户</button>
      </div>
    </div>
    <div class="z-table" style="width: 820px;">
      <el-table :data="data.list" v-loading="data.loading" size="large">
        <el-table-column prop="id" label="id" width="60px" align="center" />
        <el-table-column prop="name" label="姓名" width="120px" align="center" />
        <el-table-column prop="username" label="登录名" width="140px" align="center" />
        <el-table-column prop="userpwd" label="登录密码" width="120px" align="center" />
        <el-table-column prop="sex" label="性别" width="120px" align="center" />
        <el-table-column prop="age" label="年龄" width="120px" align="center" />
        <el-table-column label="操作" align="center" width="160">
          <template #default="scope">
            <el-button type="primary" link @click="showDrawer(2, scope.row)">编辑</el-button>
            <el-button type="danger" link @click="onDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="z-pagination" style="width: 820px;">
      <el-pagination
        background
        layout="total, prev, pager, next, sizes"
        :total="data.total"
        :page-sizes="[10, 15, 20]"
        :pageSize="data.pageSize"
        :pageIndex="data.pageIndex"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
      ></el-pagination>
    </div>
  </div>

  <!-- 删除 -->
  <el-dialog v-model="dialogVisible" title="提示" width="30%">
    <span>确认删除用户【<el-button type="danger" link>{{ deleteUser?.name }}</el-button>】吗？</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onDeleteConfim">确认</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 新增、编辑 -->
  <el-drawer v-model="drawerVisible" :title="drawerType === 1 ? '新增用户' : '编辑用户'" @close="closeDrawer">
    <div class="z-form">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" size="large" :label-position="'left'" label-width="100px">
        <el-form-item label="id" prop="id">
          <span>{{ ruleForm.id || '--' }}</span>
        </el-form-item>
        <el-form-item label="用户名" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="登录名" prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入" :disabled="drawerType === 2" />
        </el-form-item>
        <el-form-item label="密码" prop="userpwd">
          <el-input v-model="ruleForm.userpwd" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="ruleForm.sex" placeholder="请选择">
            <el-option v-for="item in sexOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input type="number" v-model="ruleForm.age" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
          <el-button type="primary" @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-drawer>
</template>

<style lang="scss" scoped>
  .test {
    position: fixed;
    width: 100vw;
    height: 100vh;
    top: 0;
    left: 0;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40px;
  }
  .btn {
    height: 40px; padding: 0 20px; outline: none; cursor: pointer; border: 0; background: linear-gradient(to top right,#41b782,#86d169);
    border-radius: 100px; font-size: 16px; position: relative; overflow: hidden;
    &::before { content: ""; position: absolute; width: 40%; height: 200%; background-color: rgba(255,255,255,.3); transform: skewX(-45deg); top: -50%; left: -50%; }
    &:hover { background: linear-gradient(to top,#86d169, #41b782); }
    &:hover::before { left: 120%; transition: left 1.5s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
  }
  .el-select { width: 100%; }
</style>